from flask import Blueprint, request, jsonify
from flask import current_app
from flask import Flask, request, jsonify
from flask_login import LoginManager, login_user, logout_user, current_user
from werkzeug.security import generate_password_hash, check_password_hash
from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity
from flask import send_from_directory
from werkzeug.exceptions import BadRequest
from flask_jwt_extended import jwt_required, get_jwt_identity, get_jwt
from datetime import timedelta
from datetime import datetime
from flask import Flask, request, jsonify
from flask_jwt_extended import create_access_token, jwt_required, JWTManager
import uuid
from ..rag.doc_processor import DocumentProcessor
from ..models import *
from llama_index.core import SimpleDirectoryReader, StorageContext
from llama_index.vector_stores.chroma import ChromaVectorStore
from llama_index.core.node_parser import SentenceSplitter
# from llama_index.embeddings.huggingface import HuggingFaceEmbedding
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader
from ..rag.embedding import SiliconFlowEmbedding
import chromadb
import os
from llama_index.llms.deepseek import DeepSeek
from llama_index.llms.openai_like import OpenAILike
# from
from datetime import datetime
# from .. import jwt
import os


bp = Blueprint('api', __name__)
# app = create_app()

# 初始化Flask-Login
# jwt = JWTManager(bp)


# 注册API（保持原逻辑，仅调整返回格式）

@bp.route('/api/register', methods=['POST'])
def register():
    data = request.get_json()

    if not data or not data.get('username') or not data.get('password'):
        return jsonify({'error': 'Username and password are required'}), 400

    if User.query.filter_by(username=data['username']).first():
        return jsonify({'error': 'Username already exists'}), 400

    try:
        new_user = User(
            username=data['username'],
            password_hash=generate_password_hash(data['password']),
            is_admin=data.get('is_admin', False)
        )
        db.session.add(new_user)
        db.session.commit()

        return jsonify({
            'message': 'User created successfully',
            'user': {  # 返回用户信息但不包含敏感数据
                'user_id': new_user.user_id,
                'username': new_user.username,
                'is_admin': new_user.is_admin
            }
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

# 登录API（改用JWT）
@bp.route('/api/login', methods=['POST'])
def login():
    data = request.get_json()

    if not data or not data.get('username') or not data.get('password'):
        return jsonify({'error': 'Username and password are required'}), 400

    user = User.query.filter_by(username=data['username']).first()

    if not user or not check_password_hash(user.password_hash, data['password']):
        return jsonify({'error': 'Invalid username or password'}), 401

    # 更新最后登录时间
    user.last_login = datetime.utcnow()
    db.session.commit()

    # # 创建JWT token（包含用户身份信息）
    # access_token = create_access_token(
    #     identity={
    #         'user_id': user.user_id,
    #         'username': user.username,
    #         'is_admin': user.is_admin
    #     },
    #     expires_delta=timedelta(hours=24)  # 设置24小时过期
    # )

    # 正确写法（identity用字符串）
    access_token = create_access_token(
        identity=str(user.user_id),  # 确保转换为字符串
        additional_claims={  # 其他信息通过claims传递
            'username': user.username,
            'is_admin': user.is_admin
        },
        expires_delta=timedelta(hours=24)  # 设置24小时过期
    )

    return jsonify({
        'message': 'Login successful',
        'access_token': access_token,
        'user': {
            'user_id': user.user_id,
            'username': user.username,
            'is_admin': user.is_admin
        }
    })

# 登出API（前端需清除本地存储的token）
@bp.route('/api/logout', methods=['POST'])
@jwt_required()
def logout():
    # JWT是无状态的，实际登出由前端删除token实现
    return jsonify({'message': 'Logout successful'})




# @bp.route('/chat')
# def serve_chat(path='chat.html'):
#     return send_from_directory('static', path)


# @bp.route('/')
# def serve_index(path='index.html'):
#     return send_from_directory('static', path)
#
#
# @bp.route('/login')
# def serve_login(path='login.html'):
#     return send_from_directory('static', path)
#
# @bp.route('/register')
# def serve_register(path='register.html'):
#     return send_from_directory('static', path)


# @bp.route('/admin')
# # @jwt_required()
# def serve_admin(path='admin_index.html'):
#     return send_from_directory('static', path)

# 新增：获取当前用户信息的保护端点
@bp.route('/api/current_user', methods=['GET'])
@jwt_required()
def current_user():
    user_id = get_jwt_identity()  # 获取字符串类型的identity
    claims = get_jwt()  # 获取全部claims
    print(claims)
    user = User.query.get(user_id)
    print(user)
    return jsonify({
        'user_id': user.user_id,
        'username': user.username,
        'is_admin': claims.get('is_admin', False)
    })

@bp.route('/api/users', methods=['GET'])
@jwt_required()
def get_all_user():
    try:
        # 获取所有用户（可根据需要添加filter条件，如is_active）
        users = User.query.all()  # 原User模型中没有is_active字段，所以移除了filter_by

        # 将用户列表转换为字典格式
        users_list = []
        for user in users:
            users_list.append({
                'user_id': user.user_id,
                'username': user.username,
                'is_admin': user.is_admin,
                'created_at': user.created_at.isoformat() if user.created_at else None,
                'last_login': user.last_login.isoformat() if user.last_login else None,
                # 注意：出于安全考虑，不返回password_hash
                'agent_count': len(user.agents)  # 添加关联的agent数量
            })

        return jsonify(users_list), 200

    except Exception as e:
        return jsonify({'error': str(e)}), 500


@bp.route('/api/users/<string:user_id>', methods=['DELETE'])
@jwt_required()
def delete_user(user_id):
    try:
        # 首先验证请求用户是否为管理员（可选，根据你的需求）
        current_user = get_jwt_identity()
        requesting_user = User.query.filter_by(user_id=current_user).first()

        if not requesting_user or not requesting_user.is_admin:
            return jsonify({'error': 'Unauthorized: Only admin users can delete users'}), 403

        # 查找要删除的用户
        user_to_delete = User.query.filter_by(user_id=user_id).first()

        if not user_to_delete:
            return jsonify({'error': 'User not found'}), 404

        # 删除用户（注意：这将级联删除关联的agents，因为模型中有relationship）
        db.session.delete(user_to_delete)
        db.session.commit()

        return jsonify({'message': f'User {user_id} deleted successfully'}), 200

    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500


# 用户编辑 API
@bp.route('/api/users/<string:user_id>', methods=['PUT'])
@jwt_required()
def update_user(user_id):
    try:
        # 验证请求用户是否为管理员
        current_user_id = get_jwt_identity()
        requesting_user = User.query.filter_by(user_id=current_user_id).first()

        if not requesting_user or not requesting_user.is_admin:
            return jsonify({'error': 'Unauthorized: Only admin users can update users'}), 403

        data = request.get_json()
        user_to_update = User.query.filter_by(user_id=user_id).first()

        if not user_to_update:
            return jsonify({'error': 'User not found'}), 404

        # 更新用户信息
        if 'username' in data:
            user_to_update.username = data['username']
        if 'password' in data and data['password']:
            user_to_update.password_hash = generate_password_hash(data['password'])
        if 'is_admin' in data:
            user_to_update.is_admin = data['is_admin']

        db.session.commit()

        return jsonify({
            'message': f'User {user_id} updated successfully',
            'user': {
                'user_id': user_to_update.user_id,
                'username': user_to_update.username,
                'is_admin': user_to_update.is_admin
            }
        }), 200

    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

# 获取单个用户信息 API
@bp.route('/api/users/<string:user_id>', methods=['GET'])
@jwt_required()
def get_user(user_id):
    try:
        # 验证请求用户权限
        current_user_id = get_jwt_identity()
        requesting_user = User.query.filter_by(user_id=current_user_id).first()

        if not requesting_user or (not requesting_user.is_admin and requesting_user.user_id != user_id):
            return jsonify({'error': 'Unauthorized'}), 403

        user = User.query.filter_by(user_id=user_id).first()

        if not user:
            return jsonify({'error': 'User not found'}), 404

        return jsonify({
            'user_id': user.user_id,
            'username': user.username,
            'is_admin': user.is_admin,
            'created_at': user.created_at.isoformat() if user.created_at else None,
            'last_login': user.last_login.isoformat() if user.last_login else None,
            'agent_count': len(user.agents)
        }), 200

    except Exception as e:
        return jsonify({'error': str(e)}), 500

# 模型编辑 API
@bp.route('/api/llm_models/<model_id>', methods=['PUT'])
@jwt_required()
def update_llm_model(model_id):
    try:
        # 获取请求数据
        data = request.get_json()
        if not data:
            raise BadRequest('No input data provided')

        # 查找要更新的模型
        model_to_update = LLMModel.query.get(model_id)
        if not model_to_update:
            return jsonify({'error': 'Model not found'}), 404

        # 更新模型信息
        if 'name' in data:
            model_to_update.name = data['name']
        if 'model_type' in data:
            model_to_update.model_type = data['model_type']
        if 'api_endpoint' in data:
            model_to_update.api_endpoint = data['api_endpoint']
        if 'api_key' in data:
            model_to_update.api_key = data['api_key']
        if 'max_tokens' in data:
            model_to_update.max_tokens = data['max_tokens']
        if 'supports_functions' in data:
            model_to_update.supports_functions = data['supports_functions']
        if 'is_active' in data:
            model_to_update.is_active = data['is_active']
        if 'description' in data:
            model_to_update.description = data['description']
        if 'provider' in data:
            model_to_update.provider = data['provider']

        db.session.commit()

        return jsonify({
            'model_id': model_to_update.model_id,
            'name': model_to_update.name,
            'status': 'updated'
        }), 200

    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

# 获取单个模型信息 API
@bp.route('/api/llm_models/<model_id>', methods=['GET'])
@jwt_required()
def get_llm_model(model_id):
    try:
        model = LLMModel.query.get(model_id)
        if not model:
            return jsonify({'error': 'Model not found'}), 404

        return jsonify({
            'model_id': model.model_id,
            'name': model.name,
            'model_type': model.model_type,
            'api_endpoint': model.api_endpoint,
            'api_key': model.api_key,
            'max_tokens': model.max_tokens,
            'supports_functions': model.supports_functions,
            'is_active': model.is_active,
            'description': model.description,
            'provider': model.provider
        }), 200

    except Exception as e:
        return jsonify({'error': str(e)}), 500

# 文档删除 API
@bp.route('/api/documents/<doc_id>', methods=['DELETE'])
@jwt_required()
def delete_document(doc_id):
    try:
        # 查找要删除的文档
        doc_to_delete = DocumentMetadata.query.filter_by(doc_id=doc_id).first()
        if not doc_to_delete:
            return jsonify({'error': 'Document not found'}), 404

        # 删除文档（需要同时从向量数据库中删除）
        # 这里需要实现从向量数据库中删除相关文档的逻辑
        # 示例代码：
        chroma_client = chromadb.PersistentClient(path=current_app.config['VECTOR_DB_PATH'])
        collection = chroma_client.get_collection("rag_docs")
        collection.delete(ids=[doc_id])

        # 从SQLite中删除文档元数据
        db.session.delete(doc_to_delete)
        db.session.commit()

        return jsonify({
            'message': f'Document {doc_id} deleted successfully',
            'doc_id': doc_id
        }), 200

    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

# 获取单个文档信息 API
@bp.route('/api/documents/<doc_id>', methods=['GET'])
@jwt_required()
def get_document(doc_id):
    try:
        doc = DocumentMetadata.query.filter_by(doc_id=doc_id).first()
        if not doc:
            return jsonify({'error': 'Document not found'}), 404

        return jsonify({
            'id': doc.id,
            'doc_id': doc.doc_id,
            'file_name': doc.file_name,
            'file_type': doc.file_type,
            'file_size': doc.file_size,
            'page_count': doc.page_count,
            'created_at': doc.created_at.isoformat(),
            'additional_metadata': doc.additional_metadata,
            'summary': doc.summary,
            'text_preview': doc.text_preview
        }), 200

    except Exception as e:
        return jsonify({'error': str(e)}), 500

# 修改密码 API
@bp.route('/api/change_password', methods=['POST'])
@jwt_required()
def change_password():
    try:
        data = request.get_json()
        if not data or not data.get('current_password') or not data.get('new_password'):
            return jsonify({'error': 'Current and new password are required'}), 400

        user_id = get_jwt_identity()
        user = User.query.filter_by(user_id=user_id).first()

        if not user or not check_password_hash(user.password_hash, data['current_password']):
            return jsonify({'error': 'Current password is incorrect'}), 401

        # 更新密码
        user.password_hash = generate_password_hash(data['new_password'])
        db.session.commit()

        return jsonify({'message': 'Password changed successfully'}), 200

    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

# 系统设置 API
@bp.route('/api/settings', methods=['GET', 'POST'])
@jwt_required()
def handle_settings():
    try:
        if request.method == 'GET':
            # 获取系统设置
            settings = {
                'system_name': '智慧Agent平台',  # 从数据库或配置文件中获取实际值
                'doc_store_path': current_app.config.get('DOCUMENT_STORE', ''),
                'vector_db_path': current_app.config.get('VECTOR_DB_PATH', ''),
                'default_model': 1  # 从数据库或配置文件中获取实际值
            }
            return jsonify(settings), 200
        else:
            # 更新系统设置
            data = request.get_json()
            # 这里应该实现将设置保存到数据库或配置文件的逻辑
            # 示例代码：
            # update_system_settings(data)
            return jsonify({'message': 'Settings updated successfully'}), 200

    except Exception as e:
        return jsonify({'error': str(e)}), 500
@bp.route('/api/llm_models', methods=['POST'])
@jwt_required()
def add_llm_model():
    # # 验证管理员权限
    # claims = get_jwt()
    # if not claims.get('is_admin', False):
    #     return jsonify({'error': 'Unauthorized'}), 403

        # 获取请求数据
    data = request.get_json()
    if not data:
        raise BadRequest('No input data provided')

        # 验证必填字段
    required_fields = ['name', 'model_type', 'api_endpoint','api_key','provider']
    for field in required_fields:
        if field not in data:
            raise BadRequest(f'Missing required field: {field}')

            # 创建新模型
    try:
        new_model = LLMModel(
            name=data['name'],
            model_type=data['model_type'],
            api_endpoint=data['api_endpoint'],
            api_key=data.get('api_key'),
            max_tokens=data.get('max_tokens', 8192),
            supports_functions=data.get('supports_functions', False),
            is_active=data.get('is_active', True),
            description=data.get('description'),
            provider=data.get('provider')
        )

        db.session.add(new_model)
        db.session.commit()

        return jsonify({
            'model_id': new_model.model_id,
            'name': new_model.name,
            'status': 'success'
        }), 201

    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@bp.route('/api/llm_models/<model_id>', methods=['DELETE'])
@jwt_required()
def delete_llm_model(model_id):
    # # 验证管理员权限
    # claims = get_jwt()
    # if not claims.get('is_admin', False):
    #     return jsonify({'error': 'Unauthorized'}), 403

    # 查找要删除的模型
    model_to_delete = LLMModel.query.get(model_id)
    if not model_to_delete:
        return jsonify({'error': 'Model not found'}), 404

    # 执行删除操作
    try:
        db.session.delete(model_to_delete)
        db.session.commit()

        return jsonify({
            'model_id': model_id,
            'name': model_to_delete.name,
            'status': 'deleted'
        }), 200

    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@bp.route('/api/get_all_llm_models', methods=['GET'])
@jwt_required()
def get_all_llm_models():
    """
    获取所有LLM模型
    ---
    tags:
      - LLM Models
    responses:
      200:
        description: 返回所有LLM模型列表
        schema:
          type: array
          items:
            $ref: '#/definitions/LLMModel'
      403:
        description: 未授权访问
      500:
        description: 服务器内部错误
    """
    try:
        # 获取所有活跃的LLM模型（可根据需要移除filter条件）
        models = LLMModel.query.filter_by(is_active=True).all()

        # 将模型列表转换为字典格式
        models_list = []
        for model in models:
            models_list.append({
                'model_id': model.model_id,
                'name': model.name,
                'model_type': model.model_type,
                'api_endpoint': model.api_endpoint,
                'max_tokens': model.max_tokens,
                'supports_functions': model.supports_functions,
                'is_active': model.is_active,
                'description': model.description,
                'provider': model.provider
            })

        return jsonify(models_list), 200

    except Exception as e:
        return jsonify({'error': str(e)}), 500

@bp.route('/api/upload', methods=['POST'])
def upload_document():

    def _extract_metadata(document):
        """提取并丰富文档元数据"""
        file_path = document.metadata.get("file_path", "")
        file_name = os.path.basename(file_path)
        file_size = os.path.getsize(file_path)

        return {
            "doc_id": document.doc_id,
            "file_name": file_name,
            "file_type": os.path.splitext(file_name)[1].lower(),
            "file_size": file_size,
            "page_count": document.metadata.get("page_label", 1),
            "created_at": datetime.now().isoformat(),
            "additional_metadata": document.metadata,
            "summary": document.text[:200] + "..." if len(document.text) > 200 else document.text,
            "text_preview": document.text[:1000]  # 存储部分文本用于预览
        }
    """处理文档上传"""
    if 'file' not in request.files:
        return jsonify({"error": "No file part"}), 400

    file = request.files['file']
    if file.filename == '':
        return jsonify({"error": "No selected file"}), 400

    # 保存上传的文件
    file_path = os.path.join(current_app.config['DOCUMENT_STORE'], file.filename)
    file.save(file_path)

    try:
        # 处理文档

        embed_model  = SiliconFlowEmbedding(
            model_name="netease-youdao/bce-embedding-base_v1",
            api_key="Bearer sk-ngekgvpblpqccnltgqydfzdxsktivlwmaoyjdfklsdjsadtz"
        )

        # 初始化Chroma客户端
        chroma_client = chromadb.PersistentClient(path=current_app.config['VECTOR_DB_PATH'])
        vector_store = ChromaVectorStore(
            chroma_collection=chroma_client.get_or_create_collection("rag_docs")
        )

        # 初始化文本分割器
        splitter = SentenceSplitter(
            chunk_size=128,
            chunk_overlap=50,
            separator=" ",
            paragraph_separator="\n\n"
        )

        reader = SimpleDirectoryReader(input_files=[file_path])
        documents = reader.load_data()

        for doc in documents:
            # 处理元数据
            metadata = _extract_metadata(doc)

            # 存储元数据到SQLite
            record = DocumentMetadata(
                doc_id=metadata["doc_id"],
                file_name=metadata["file_name"],
                file_type=metadata["file_type"],
                file_size=metadata["file_size"],
                page_count=metadata["page_count"],
                created_at=metadata["created_at"],
                additional_metadata=metadata["additional_metadata"],
                summary=metadata["summary"],
                text_preview=metadata["text_preview"]
            )
            #降record写入DocumentMetadata数据库
            # new_user = User(username=username, email=email, password=hashed_password)
            db.session.add(record)
            db.session.commit()

        nodes = splitter.get_nodes_from_documents(documents)

        # 创建存储上下文
        storage_context = StorageContext.from_defaults(
            vector_store=vector_store
        )

        # 构建索引
        index = VectorStoreIndex(
            nodes,
            storage_context=storage_context,
            embed_model=embed_model
        )

        return jsonify({
            "status": "success",
            "message": "Document processed successfully"
        }), 200
    except Exception as e:
        return jsonify({
            "error": str(e)
        }), 500




@bp.route('/api/query', methods=['POST'])
@jwt_required()
def handle_query():
    """处理用户查询"""
    data = request.get_json()
    query = data.get('query', '')

    if not query:
        return jsonify({"error": "Empty query"}), 400

    try:
        # processor = DocumentProcessor(chroma_path=current_app.config['VECTOR_DB_PATH'])
        # query_engine = processor.get_query_engine()
        # response = query_engine.query(query)



        embed_model  = SiliconFlowEmbedding(
            model_name="netease-youdao/bce-embedding-base_v1",
            api_key="Bearer sk-ngekgvpblpqccnltgqydfzdxsktivlwmaoyjdfklsdjsadtz"
        )

        # 初始化Chroma客户端
        chroma_client = chromadb.PersistentClient(path=current_app.config['VECTOR_DB_PATH'])
        vector_store = ChromaVectorStore(
            chroma_collection=chroma_client.get_or_create_collection("rag_docs")
        )
        index = VectorStoreIndex.from_vector_store(
            vector_store,
            embed_model=embed_model
        )

        llm = DeepSeek(model="deepseek-chat", api_key="sk-7dfdb92a297e47d498ad94ca385ab51c")
        query_engine = index.as_query_engine(
            similarity_top_k=5,
            response_mode="compact",
            llm=llm,
            verbose=True
        )
        # query_engine = processor.get_query_engine()
        response = query_engine.query(query)

        return jsonify({
            "response": str(response),
            "sources": [{
                "text": node.text,
                "metadata": node.metadata
            } for node in response.source_nodes]
        }), 200
    except Exception as e:
        return jsonify({
            "error": str(e)
        }), 500


@bp.route('/api/documents', methods=['GET'])
def list_documents():
    """列出已处理的文档"""
    try:
        # session = Session()
        # documents = session.query(DocumentMetadata).all()
        documents=DocumentMetadata.query.all()
        return jsonify([{
            "id": doc.id,
            "doc_id": doc.doc_id,
            "file_name": doc.file_name,
            "file_type": doc.file_type,
            "file_size": doc.file_size,
            "created_at": doc.created_at,
            "summary": doc.summary
        } for doc in documents]), 200
    except Exception as e:
        return jsonify({
            "error": str(e)
        }), 500


# Agent 创建 API
@bp.route('/api/agents', methods=['POST'])
@jwt_required()
def create_agent():
    try:
        # 获取当前用户ID
        current_user_id = get_jwt_identity()
        data = request.get_json()

        # 验证必填字段
        required_fields = ['name', 'llm_model_id']
        for field in required_fields:
            if field not in data:
                return jsonify({'error': f'Missing required field: {field}'}), 400

        # 验证LLM模型是否存在
        llm_model = LLMModel.query.filter_by(model_id=data['llm_model_id'], is_active=True).first()
        if not llm_model:
            return jsonify({'error': 'Specified LLM model not found or inactive'}), 400

        # 创建新Agent
        new_agent = Agent(
            name=data['name'],
            llm_model_id=data['llm_model_id'],
            creator_id=current_user_id,
            greeting_message=data.get('greeting_message', "你好，我是AI助理，有什么可以帮您？"),
            system_prompt=data.get('system_prompt'),
            temperature=data.get('temperature', 0.7),
            max_tokens=data.get('max_tokens', 2048)
        )

        db.session.add(new_agent)
        db.session.commit()

        return jsonify({
            'message': 'Agent created successfully',
            'agent': {
                'agent_id': new_agent.agent_id,
                'name': new_agent.name,
                'llm_model_id': new_agent.llm_model_id,
                'creator_id': new_agent.creator_id,
                'greeting_message': new_agent.greeting_message,
                'created_at': new_agent.created_at.isoformat(),
                'is_active': new_agent.is_active
            }
        }), 201

    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500


# 获取所有Agent API
@bp.route('/api/agents', methods=['GET'])
@jwt_required()
def get_all_agents():
    try:
        # 获取当前用户ID
        current_user_id = get_jwt_identity()

        # 检查是否是管理员
        claims = get_jwt()
        is_admin = claims.get('is_admin', False)

        # 管理员可以查看所有Agent，普通用户只能查看自己创建的Agent
        if is_admin:
            agents = Agent.query.all()
        else:
            agents = Agent.query.filter_by(creator_id=current_user_id).all()

        # 转换为字典格式
        agents_list = []
        for agent in agents:
            agents_list.append({
                'agent_id': agent.agent_id,
                'name': agent.name,
                'llm_model_id': agent.llm_model_id,
                'llm_model_name': agent.llm_model.name if agent.llm_model else None,
                'creator_id': agent.creator_id,
                'creator_name': agent.creator.username if agent.creator else None,
                'greeting_message': agent.greeting_message,
                'created_at': agent.created_at.isoformat(),
                'updated_at': agent.updated_at.isoformat(),
                'is_active': agent.is_active,
                'system_prompt': agent.system_prompt,
                'temperature': agent.temperature,
                'max_tokens': agent.max_tokens,
                'knowledge_base_count': len(agent.knowledge_bases)
            })

        return jsonify(agents_list), 200

    except Exception as e:
        return jsonify({'error': str(e)}), 500


# 获取单个Agent详细信息 API
@bp.route('/api/agents/<string:agent_id>', methods=['GET'])
@jwt_required()
def get_agent(agent_id):
    try:
        # 获取当前用户ID
        current_user_id = get_jwt_identity()

        # 查找Agent
        agent = Agent.query.filter_by(agent_id=agent_id).first()
        if not agent:
            return jsonify({'error': 'Agent not found'}), 404

        # 检查权限（管理员或创建者）
        claims = get_jwt()
        is_admin = claims.get('is_admin', False)
        if not is_admin and agent.creator_id != current_user_id:
            return jsonify({'error': 'Unauthorized to access this agent'}), 403

        # 获取关联的知识库信息
        knowledge_bases = []
        for kb in agent.knowledge_bases:
            knowledge_bases.append({
                'kb_id': kb.kb_id,
                'name': kb.name,
                'description': kb.description,
                'created_at': kb.created_at.isoformat()
            })

        return jsonify({
            'agent_id': agent.agent_id,
            'name': agent.name,
            'llm_model_id': agent.llm_model_id,
            'llm_model_name': agent.llm_model.name if agent.llm_model else None,
            'creator_id': agent.creator_id,
            'creator_name': agent.creator.username if agent.creator else None,
            'greeting_message': agent.greeting_message,
            'created_at': agent.created_at.isoformat(),
            'updated_at': agent.updated_at.isoformat(),
            'is_active': agent.is_active,
            'system_prompt': agent.system_prompt,
            'temperature': agent.temperature,
            'max_tokens': agent.max_tokens,
            'knowledge_bases': knowledge_bases
        }), 200

    except Exception as e:
        return jsonify({'error': str(e)}), 500


# 更新Agent API
@bp.route('/api/agents/<string:agent_id>', methods=['PUT'])
@jwt_required()
def update_agent(agent_id):
    try:
        # 获取当前用户ID
        current_user_id = get_jwt_identity()
        data = request.get_json()

        # 查找Agent
        agent = Agent.query.filter_by(agent_id=agent_id).first()
        if not agent:
            return jsonify({'error': 'Agent not found'}), 404

        # 检查权限（管理员或创建者）
        claims = get_jwt()
        is_admin = claims.get('is_admin', False)
        if not is_admin and agent.creator_id != current_user_id:
            return jsonify({'error': 'Unauthorized to update this agent'}), 403

        # 更新可修改字段
        if 'name' in data:
            agent.name = data['name']
        if 'greeting_message' in data:
            agent.greeting_message = data['greeting_message']
        if 'system_prompt' in data:
            agent.system_prompt = data['system_prompt']
        if 'temperature' in data:
            agent.temperature = data['temperature']
        if 'max_tokens' in data:
            agent.max_tokens = data['max_tokens']
        if 'is_active' in data:
            # 只有管理员可以修改is_active状态
            if is_admin:
                agent.is_active = data['is_active']
            else:
                return jsonify({'error': 'Only admin can change agent active status'}), 403
        if 'llm_model_id' in data:
            # 验证新的LLM模型是否存在
            llm_model = LLMModel.query.filter_by(model_id=data['llm_model_id'], is_active=True).first()
            if not llm_model:
                return jsonify({'error': 'Specified LLM model not found or inactive'}), 400
            agent.llm_model_id = data['llm_model_id']

        db.session.commit()

        return jsonify({
            'message': 'Agent updated successfully',
            'agent': {
                'agent_id': agent.agent_id,
                'name': agent.name,
                'llm_model_id': agent.llm_model_id,
                'greeting_message': agent.greeting_message,
                'is_active': agent.is_active,
                'updated_at': agent.updated_at.isoformat()
            }
        }), 200

    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500


# 删除Agent API
@bp.route('/api/agents/<string:agent_id>', methods=['DELETE'])
@jwt_required()
def delete_agent(agent_id):
    try:
        # 获取当前用户ID
        current_user_id = get_jwt_identity()

        # 查找Agent
        agent = Agent.query.filter_by(agent_id=agent_id).first()
        if not agent:
            return jsonify({'error': 'Agent not found'}), 404

        # 检查权限（管理员或创建者）
        claims = get_jwt()
        is_admin = claims.get('is_admin', False)
        if not is_admin and agent.creator_id != current_user_id:
            return jsonify({'error': 'Unauthorized to delete this agent'}), 403

        # 删除Agent
        db.session.delete(agent)
        db.session.commit()

        return jsonify({
            'message': 'Agent deleted successfully',
            'agent_id': agent_id
        }), 200

    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500


@bp.route('/api/agents/chat/<string:agent_id>', methods=['POST'])
@jwt_required()
def chat_agent(agent_id):
    try:
        # 获取当前用户ID

        """处理用户查询"""
        data = request.get_json()
        query = data.get('query', '')
        if not query:
            return jsonify({'error': 'No query provided'}), 400
        current_user_id = get_jwt_identity()

        # 查找Agent
        agent = Agent.query.filter_by(agent_id=agent_id).first()
        if not agent:
            return jsonify({'error': 'Agent not found'}), 404

        # processor = DocumentProcessor(chroma_path=current_app.config['VECTOR_DB_PATH'])
        # query_engine = processor.get_query_engine()
        # response = query_engine.query(query)

        if len(agent.knowledge_bases) != 0:

            kb = agent.knowledge_bases[0]

            # embed_model = SiliconFlowEmbedding(
            #     model_name="netease-youdao/bce-embedding-base_v1",
            #     api_key="Bearer sk-ngekgvpblpqccnltgqydfzdxsktivlwmaoyjdfklsdjsadtz"
            # )

            embed_model = SiliconFlowEmbedding(
                model_name=LLMModel.query.filter_by(model_id=kb.embedding_model_id).first().name,
                api_key="Bearer "+LLMModel.query.filter_by(model_id=kb.embedding_model_id).first().api_key
            )

            # 这会返回一个包含所有关联知识库的列表
            # for kb in agent_knowledge:
            #     print(kb.name, kb.vector_db_path)
            # # 初始化Chroma客户端
            # chroma_client = chromadb.PersistentClient(path=current_app.config['VECTOR_DB_PATH'])
            # vector_store = ChromaVectorStore(
            #     chroma_collection=chroma_client.get_or_create_collection("rag_docs")
            # )

            # 1. 连接已有 Chroma 数据库
            chroma_client = chromadb.PersistentClient(path=kb.vector_db_path)  # 或 HttpClient(host,port)
            collection = chroma_client.get_collection("rag_docs")

            # 2. 创建 VectorStore
            vector_store = ChromaVectorStore(chroma_collection=collection)


            index = VectorStoreIndex.from_vector_store(
                vector_store,
                embed_model=embed_model
            )

            llm=LLMModel.query.filter_by(model_id=agent.llm_model_id).first()

            class_map = {
                "DeepSeek": DeepSeek,
                "OpenAILike":OpenAILike,
                "SiliconFlow":OpenAILike,
                "api2d":OpenAILike
                # 其他模型类...
            }
            print(llm)
            print((llm.name,llm.api_key))
            llm = class_map[llm.provider](model=llm.name,api_key=llm.api_key,api_base=llm.api_endpoint)
            # llm = DeepSeek(model="deepseek-chat", api_key="sk-7dfdb92a297e47d498ad94ca385ab51c")
            query_engine = index.as_query_engine(
                similarity_top_k=5,
                response_mode="compact",
                llm=llm,
                verbose=True
            )
            # query_engine = processor.get_query_engine()
            response = query_engine.query(query)
            print(response)
            return jsonify({
                "response": str(response),
                "sources": [{
                    "text": node.text,
                    "metadata": node.metadata
                } for node in response.source_nodes]
            }), 200
        else:
            llm = LLMModel.query.filter_by(model_id=agent.llm_model_id).first()

            class_map = {
                "DeepSeek": DeepSeek,
                "OpenAILike": OpenAILike,
                "SiliconFlow": OpenAILike,
                "api2d": OpenAILike
                # 其他模型类...
            }
            print(llm)
            print((llm.name, llm.api_key))
            llm = class_map[llm.provider](model=llm.name, api_key=llm.api_key, api_base=llm.api_endpoint)
            response = llm.complete(query)
            return jsonify({
                "response": str(response),
                "sources":[]
            }), 200

    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

# 关联知识库到Agent API
@bp.route('/api/agents/<string:agent_id>/knowledge_bases', methods=['POST'])
@jwt_required()
def link_knowledge_base_to_agent(agent_id):
    try:
        # 获取当前用户ID
        current_user_id = get_jwt_identity()
        data = request.get_json()

        # 验证必填字段
        if 'kb_id' not in data:
            return jsonify({'error': 'Missing required field: kb_id'}), 400

        # 查找Agent
        agent = Agent.query.filter_by(agent_id=agent_id).first()
        if not agent:
            return jsonify({'error': 'Agent not found'}), 404

        # 检查权限（管理员或创建者）
        claims = get_jwt()
        is_admin = claims.get('is_admin', False)
        if not is_admin and agent.creator_id != current_user_id:
            return jsonify({'error': 'Unauthorized to modify this agent'}), 403

        # 查找知识库
        knowledge_base = KnowledgeBase.query.filter_by(kb_id=data['kb_id']).first()
        if not knowledge_base:
            return jsonify({'error': 'Knowledge base not found'}), 404

        # 检查是否已经关联
        if knowledge_base in agent.knowledge_bases:
            return jsonify({'error': 'Knowledge base already linked to this agent'}), 400

        # 建立关联
        agent.knowledge_bases.append(knowledge_base)
        db.session.commit()

        return jsonify({
            'message': 'Knowledge base linked to agent successfully',
            'agent_id': agent_id,
            'kb_id': data['kb_id']
        }), 200

    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500


# 从Agent移除知识库关联 API
@bp.route('/api/agents/<string:agent_id>/knowledge_bases/<string:kb_id>', methods=['DELETE'])
@jwt_required()
def unlink_knowledge_base_from_agent(agent_id, kb_id):
    try:
        # 获取当前用户ID
        current_user_id = get_jwt_identity()

        # 查找Agent
        agent = Agent.query.filter_by(agent_id=agent_id).first()
        if not agent:
            return jsonify({'error': 'Agent not found'}), 404

        # 检查权限（管理员或创建者）
        claims = get_jwt()
        is_admin = claims.get('is_admin', False)
        if not is_admin and agent.creator_id != current_user_id:
            return jsonify({'error': 'Unauthorized to modify this agent'}), 403

        # 查找知识库
        knowledge_base = KnowledgeBase.query.filter_by(kb_id=kb_id).first()
        if not knowledge_base:
            return jsonify({'error': 'Knowledge base not found'}), 404

        # 检查是否已经关联
        if knowledge_base not in agent.knowledge_bases:
            return jsonify({'error': 'Knowledge base not linked to this agent'}), 400

        # 移除关联
        agent.knowledge_bases.remove(knowledge_base)
        db.session.commit()

        return jsonify({
            'message': 'Knowledge base unlinked from agent successfully',
            'agent_id': agent_id,
            'kb_id': kb_id
        }), 200

    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500


# 获取用户创建的Agent API
@bp.route('/api/users/<string:user_id>/agents', methods=['GET'])
@jwt_required()
def get_user_agents(user_id):
    try:
        # 检查权限（管理员或查看自己的Agent）
        current_user_id = get_jwt_identity()
        claims = get_jwt()
        is_admin = claims.get('is_admin', False)

        if not is_admin and current_user_id != user_id:
            return jsonify({'error': 'Unauthorized to access these agents'}), 403

        # 查找用户
        user = User.query.filter_by(user_id=user_id).first()
        if not user:
            return jsonify({'error': 'User not found'}), 404

        # 获取用户创建的Agent
        agents = Agent.query.filter_by(creator_id=user_id).all()

        # 转换为字典格式
        agents_list = []
        for agent in agents:
            agents_list.append({
                'agent_id': agent.agent_id,
                'name': agent.name,
                'llm_model_id': agent.llm_model_id,
                'llm_model_name': agent.llm_model.name if agent.llm_model else None,
                'greeting_message': agent.greeting_message,
                'created_at': agent.created_at.isoformat(),
                'updated_at': agent.updated_at.isoformat(),
                'is_active': agent.is_active,
                'knowledge_base_count': len(agent.knowledge_bases)
            })

        return jsonify({
            'user_id': user_id,
            'username': user.username,
            'agents': agents_list,
            'count': len(agents_list)
        }), 200

    except Exception as e:
        return jsonify({'error': str(e)}), 500

# 知识库创建 API
@bp.route('/api/knowledge_bases', methods=['POST'])
@jwt_required()
def create_knowledge_base():
    try:
        # 获取当前用户ID
        current_user_id = get_jwt_identity()
        data = request.get_json()

        # 验证必填字段
        required_fields = ['name', 'embedding_model_id']
        for field in required_fields:
            if field not in data:
                return jsonify({'error': f'Missing required field: {field}'}), 400

        # 验证嵌入模型是否存在
        embedding_model = LLMModel.query.filter_by(
            model_id=data['embedding_model_id'],
            model_type='embedding',
            is_active=True
        ).first()
        if not embedding_model:
            return jsonify({'error': 'Specified embedding model not found or inactive'}), 400

        # 创建知识库唯一路径
        kb_id = str(uuid.uuid4())
        kid = kb_id
        vector_db_path = os.path.join(
                current_app.config['VECTOR_DB_PATH'],
                f"kb_{kb_id}"
            )

        # 创建新知识库
        new_kb = KnowledgeBase(
            kb_id=kb_id,
            name=data['name'],
            embedding_model_id=data['embedding_model_id'],
            vector_db_path=vector_db_path,
            description=data.get('description', ''),
            creator_id=current_user_id,
            is_public=data.get('is_public', False),
            chunk_size=data.get('chunk_size', 512),
            chunk_overlap=data.get('chunk_overlap', 50)
        )

        db.session.add(new_kb)
        db.session.commit()

        # 创建对应的向量数据库目录
        os.makedirs(vector_db_path, exist_ok=True)

        return jsonify({
            'message': 'Knowledge base created successfully',
            'knowledge_base': {
                'kb_id': new_kb.kb_id,
                'name': new_kb.name,
                'embedding_model_id': new_kb.embedding_model_id,
                'created_at': new_kb.created_at.isoformat(),
                'description': new_kb.description,
                'is_public': new_kb.is_public
            }
        }), 201

    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

# 获取所有知识库 API
@bp.route('/api/knowledge_bases', methods=['GET'])
@jwt_required()
def get_all_knowledge_bases():
    try:
        # 获取当前用户ID
        current_user_id = get_jwt_identity()

        # 检查是否是管理员
        claims = get_jwt()
        is_admin = claims.get('is_admin', False)

        # 管理员可以查看所有知识库，普通用户只能查看自己创建的和公开的知识库
        if is_admin:
            knowledge_bases = KnowledgeBase.query.all()
        else:
            knowledge_bases = KnowledgeBase.query.filter(
                (KnowledgeBase.creator_id == current_user_id) |
                (KnowledgeBase.is_public == True)
            ).all()

        # 转换为字典格式
        kb_list = []
        for kb in knowledge_bases:
            kb_list.append({
                'kb_id': kb.kb_id,
                'name': kb.name,
                'embedding_model_id': kb.embedding_model_id,
                'embedding_model_name': kb.embedding_model.name if kb.embedding_model else None,
                'creator_id': kb.creator_id,
                'creator_name':User.query.filter_by(user_id=kb.creator_id).first().username if kb.creator_id else None,
                'description': kb.description,
                'created_at': kb.created_at.isoformat(),
                'updated_at': kb.updated_at.isoformat(),
                'documents_count': kb.documents_count,
                'size': kb.size,
                'is_public': kb.is_public,
                'agent_count': len(kb.agents)
            })

        return jsonify(kb_list), 200

    except Exception as e:
        return jsonify({'error': str(e)}), 500

# 获取单个知识库详细信息 API
@bp.route('/api/knowledge_bases/<string:kb_id>', methods=['GET'])
@jwt_required()
def get_knowledge_base(kb_id):
    try:
        # 获取当前用户ID
        current_user_id = get_jwt_identity()

        # 查找知识库
        kb = KnowledgeBase.query.filter_by(kb_id=kb_id).first()
        if not kb:
            return jsonify({'error': 'Knowledge base not found'}), 404

        # 检查权限（管理员、创建者或公开知识库）
        claims = get_jwt()
        is_admin = claims.get('is_admin', False)
        if not is_admin and kb.creator_id != current_user_id and not kb.is_public:
            return jsonify({'error': 'Unauthorized to access this knowledge base'}), 403

        # 获取关联的Agent信息
        agents = []
        for agent in kb.agents:
            print(agents)
            agents.append({
                'agent_id': agent.agent_id,
                'name': agent.name,
                'creator_name': agent.creator.username if agent.creator else None
            })

        return jsonify({
            'kb_id': kb.kb_id,
            'name': kb.name,
            'embedding_model_id': kb.embedding_model_id,
            'embedding_model_name': kb.embedding_model.name if kb.embedding_model else None,
            'vector_db_path': kb.vector_db_path,
            'creator_id': kb.creator_id,
            'creator_name': User.query.filter_by(user_id=kb.creator_id).first().username if kb.creator_id else None,
            'description': kb.description,
            'created_at': kb.created_at.isoformat(),
            'updated_at': kb.updated_at.isoformat(),
            'documents_count': kb.documents_count,
            'size': kb.size,
            'is_public': kb.is_public,
            'chunk_size': kb.chunk_size,
            'chunk_overlap': kb.chunk_overlap,
            'agents': agents
        }), 200

    except Exception as e:
        return jsonify({'error': str(e)}), 500

# 更新知识库 API
@bp.route('/api/knowledge_bases/<string:kb_id>', methods=['PUT'])
@jwt_required()
def update_knowledge_base(kb_id):
    try:
        # 获取当前用户ID
        current_user_id = get_jwt_identity()
        data = request.get_json()

        # 查找知识库
        kb = KnowledgeBase.query.filter_by(kb_id=kb_id).first()
        if not kb:
            return jsonify({'error': 'Knowledge base not found'}), 404

        # 检查权限（管理员或创建者）
        claims = get_jwt()
        is_admin = claims.get('is_admin', False)
        if not is_admin and kb.creator_id != current_user_id:
            return jsonify({'error': 'Unauthorized to update this knowledge base'}), 403

        # 更新可修改字段
        if 'name' in data:
            kb.name = data['name']
        if 'description' in data:
            kb.description = data['description']
        if 'chunk_size' in data:
            kb.chunk_size = data['chunk_size']
        if 'chunk_overlap' in data:
            kb.chunk_overlap = data['chunk_overlap']
        if 'is_public' in data:
            # 只有管理员可以修改公开状态
            if is_admin:
                kb.is_public = data['is_public']
            else:
                return jsonify({'error': 'Only admin can change knowledge base public status'}), 403
        if 'embedding_model_id' in data:
            # 验证新的嵌入模型是否存在
            embedding_model = LLMModel.query.filter_by(
                model_id=data['embedding_model_id'],
                model_type='embedding',
                is_active=True
            ).first()
            if not embedding_model:
                return jsonify({'error': 'Specified embedding model not found or inactive'}), 400
            kb.embedding_model_id = data['embedding_model_id']

        db.session.commit()

        return jsonify({
            'message': 'Knowledge base updated successfully',
            'knowledge_base': {
                'kb_id': kb.kb_id,
                'name': kb.name,
                'description': kb.description,
                'is_public': kb.is_public,
                'updated_at': kb.updated_at.isoformat()
            }
        }), 200

    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

# 删除知识库 API
@bp.route('/api/knowledge_bases/<string:kb_id>', methods=['DELETE'])
@jwt_required()
def delete_knowledge_base(kb_id):
    try:
        # 获取当前用户ID
        current_user_id = get_jwt_identity()

        # 查找知识库
        kb = KnowledgeBase.query.filter_by(kb_id=kb_id).first()
        if not kb:
            return jsonify({'error': 'Knowledge base not found'}), 404

        # 检查权限（管理员或创建者）
        claims = get_jwt()
        is_admin = claims.get('is_admin', False)
        if not is_admin and kb.creator_id != current_user_id:
            return jsonify({'error': 'Unauthorized to delete this knowledge base'}), 403

        # 检查是否有Agent关联
        if kb.agents:
            return jsonify({
                'error': 'Cannot delete knowledge base that is linked to agents',
                'linked_agents': [agent.agent_id for agent in kb.agents]
            }), 400

        # 删除向量数据库文件
        if os.path.exists(kb.vector_db_path):
            import shutil
            shutil.rmtree(kb.vector_db_path)

        # 删除知识库记录
        db.session.delete(kb)
        db.session.commit()

        return jsonify({
            'message': 'Knowledge base deleted successfully',
            'kb_id': kb_id
        }), 200

    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

# 获取知识库中的文档列表 API
@bp.route('/api/knowledge_bases/<string:kb_id>/documents', methods=['GET'])
@jwt_required()
def get_knowledge_base_documents(kb_id):
    try:
        # 获取当前用户ID
        current_user_id = get_jwt_identity()

        # 查找知识库
        kb = KnowledgeBase.query.filter_by(kb_id=kb_id).first()
        if not kb:
            return jsonify({'error': 'Knowledge base not found'}), 404

        # 检查权限（管理员、创建者或公开知识库）
        claims = get_jwt()
        is_admin = claims.get('is_admin', False)
        if not is_admin and kb.creator_id != current_user_id and not kb.is_public:
            return jsonify({'error': 'Unauthorized to access this knowledge base'}), 403

        # 获取知识库中的文档
        # 这里需要根据您的实际实现来获取特定知识库的文档
        # 假设我们有一个DocumentMetadata模型与知识库关联
        documents = DocumentMetadata.query.all()  # 这里需要修改为实际查询逻辑
        documents=DocumentMetadata.query.filter_by(kid=kb_id).all()

        return jsonify([{
            "id": doc.id,
            "doc_id": doc.doc_id,
            "file_name": doc.file_name,
            "file_type": doc.file_type,
            "file_size": doc.file_size,
            "created_at": doc.created_at,
            "summary": doc.summary
        } for doc in documents]), 200

    except Exception as e:
        return jsonify({'error': str(e)}), 500

# 上传文档到知识库 API
@bp.route('/api/knowledge_bases/<string:kb_id>/upload', methods=['POST'])
@jwt_required()
def upload_to_knowledge_base(kb_id):
    def _extract_metadata(document):
        """提取并丰富文档元数据"""
        file_path = document.metadata.get("file_path", "")
        file_name = os.path.basename(file_path)
        file_size = os.path.getsize(file_path)

        return {
            "doc_id": document.doc_id,
            "file_name": file_name,
            "file_type": os.path.splitext(file_name)[1].lower(),
            "file_size": file_size,
            "page_count": document.metadata.get("page_label", 1),
            "created_at": datetime.now().isoformat(),
            "additional_metadata": document.metadata,
            "summary": document.text[:200] + "..." if len(document.text) > 200 else document.text,
            "text_preview": document.text[:1000]  # 存储部分文本用于预览
        }

    try:
        # 获取当前用户ID
        current_user_id = get_jwt_identity()

        # 查找知识库
        kb = KnowledgeBase.query.filter_by(kb_id=kb_id).first()
        if not kb:
            return jsonify({"error": "Knowledge base not found"}), 404

        # 检查权限（管理员或创建者）
        claims = get_jwt()
        is_admin = claims.get('is_admin', False)
        if not is_admin and kb.creator_id != current_user_id:
            return jsonify({"error": "Unauthorized to upload to this knowledge base"}), 403

        if 'file' not in request.files:
            return jsonify({"error": "No file part"}), 400

        file = request.files['file']
        if file.filename == '':
            return jsonify({"error": "No selected file"}), 400

        # 保存上传的文件
        upload_dir = os.path.join(current_app.config['DOCUMENT_STORE'], kb_id)
        os.makedirs(upload_dir, exist_ok=True)
        file_path = os.path.join(upload_dir, file.filename)
        file.save(file_path)


        print("Embedding model:", LLMModel.query.filter_by(model_id=kb.embedding_model_id).first().name)
        print("Embedding model API key:", LLMModel.query.filter_by(model_id=kb.embedding_model_id).first().api_key)
        # 处理文档
        embed_model = SiliconFlowEmbedding(
            model_name=LLMModel.query.filter_by(model_id=kb.embedding_model_id).first().name,
            api_key="Bearer "+LLMModel.query.filter_by(model_id=kb.embedding_model_id).first().api_key
        )

        # 初始化Chroma客户端 - 使用知识库特定的向量数据库路径
        chroma_client = chromadb.PersistentClient(path=kb.vector_db_path)
        vector_store = ChromaVectorStore(
            chroma_collection=chroma_client.get_or_create_collection("rag_docs")
        )

        # 初始化文本分割器 - 使用知识库配置的分块参数
        splitter = SentenceSplitter(
            chunk_size=kb.chunk_size,
            chunk_overlap=kb.chunk_overlap,
            separator=" ",
            paragraph_separator="\n\n"
        )

        reader = SimpleDirectoryReader(input_files=[file_path])
        documents = reader.load_data()

        for doc in documents:
            # 处理元数据
            metadata = _extract_metadata(doc)

            # 存储元数据到SQLite
            record = DocumentMetadata(
                doc_id=metadata["doc_id"],
                file_name=metadata["file_name"],
                file_type=metadata["file_type"],
                file_size=metadata["file_size"],
                page_count=metadata["page_count"],
                created_at=metadata["created_at"],
                additional_metadata=metadata["additional_metadata"],
                summary=metadata["summary"],
                text_preview=metadata["text_preview"],
                kid=kb_id  # 关联到知识库
            )
            db.session.add(record)
            db.session.commit()

            # 更新知识库文档计数和大小
            kb.documents_count += 1
            kb.size += metadata["file_size"]
            db.session.commit()

        nodes = splitter.get_nodes_from_documents(documents)

        # 创建存储上下文
        storage_context = StorageContext.from_defaults(
            vector_store=vector_store
        )

        # 构建索引
        index = VectorStoreIndex(
            nodes,
            storage_context=storage_context,
            embed_model=embed_model
        )

        return jsonify({
            "status": "success",
            "message": "Document processed and added to knowledge base successfully",
            "kb_id": kb_id,
            "documents_added": len(documents),
            "new_documents_count": kb.documents_count
        }), 200

    except Exception as e:
        db.session.rollback()
        return jsonify({
            "error": str(e)
        }), 500